import { Application } from 'egg';
interface IRoutes {
  [propName: string]: IRoute[];
}
interface IRoute {
  name?: string;
  method: string;
  path: string;
  controller: string;
  action: string;
  jwt?: boolean;
}
const prefix = '/api';
const createRoute = (app: Application) => {
  const { controller, router } = app;
  const routes:IRoutes = {
    // 无需鉴权的路由
    base: [
      {
        name: '首页',
        method: 'get',
        path: '/',
        controller: 'home', // 控制器路径
        action: 'index', // 控制器方法
      },
      {
        name: '登陆',
        method: 'post',
        path: '/system/login',
        controller: 'system.login', // 控制器路径
        action: 'login', // 控制器方法
      },
      {
        name: '验证码',
        method: 'get',
        path: '/system/captcha',
        controller: 'system.login', // 控制器路径
        action: 'captcha', // 控制器方法
      },
    ],
    route: [
      {
        name: '路由列表',
        method: 'get',
        path: '/system/getRoute',
        controller: 'system.route.index',
        action: 'getRoutes',
        jwt: true,
      },
    ],
  };
  // 注册路由
  Object.keys(routes).forEach((key: string) => {
    routes[key].forEach((route: IRoute) => {
      const path = callDeepProp(controller, route.controller);
      if (!path) return;
      // 是否需要鉴权
      if (route.jwt) {
        router[route.method](`${ prefix }${ route.path }`, path[route.action]);
      } else {
        router[route.method](`${ prefix }${ route.path }`, path[route.action]);
      }
    });
  });
};
function callDeepProp(obj: object, path: string) {
  const props: string[] = path.split('.');
  let result:object = obj;
  props.forEach(prop => {
    if (!result) return null;
    result = result[prop];
  });
  return result;
}

export default (app: Application) => {
  createRoute(app);
};
